<?php

namespace App\Services\Pay;

class CzbankService
{
    protected $czbank_encrypt_str;

    public $czbank_prepaid;

    public $czbank_unpaid;

    protected $api_url = [
        'confirm_pay' => ['post', 'confirmPay'],
    ];

    public function __construct()
    {
        $this->czbank_encrypt_str = config('pay')['czbank_encrypt_str'];
        $this->czbank_prepaid = config('pay')['czbank_prepaid'];
        $this->czbank_unpaid = config('pay')['czbank_unpaid'];
    }

    /**
     * 通知浙商放款
     * @param $trade_no
     * @param $czbank_no
     */
    public function loan($trade_no, $czbank_no, $order_money)
    {
        $data = [
            'tradeNo' => $trade_no,
            'totalAmount' => $order_money,
            'payAmount' => $order_money,
            'receiptAmount' => $order_money,
            'receiptSerialNo' => $czbank_no,
            'access_key' => $this->generateLoanKey($trade_no, $czbank_no)
        ];

        $ret = http_czbank($this->api_url['confirm_pay'])->send($data);

        if($ret['code'] == 0){
            return true;
        }else{
            return false;
        }
    }

    /************以下为验签过程*************/

    /**
     * 校验订单并生成流水号时使用：校验key
     * @param $key
     * @param $order_codes
     * @param $money
     * @return bool
     */
    public function checkKey($key, $order_codes, $money)
    {
        $accept_key = $this->czbank_encrypt_str . $order_codes . number_format($money, 2, '.', '');
        return strtoupper(md5($accept_key)) == strtoupper($key) ? true : false;
    }

    /**
     * 校验订单并生成流水号时使用：生成key
     * @param $order_codes
     * @param $money
     * @param $receipt_info 收款人列表
     * @return string
     */
    public function generateKey($order_codes, $money, $receipt_info)
    {
        $accept_key = $this->czbank_encrypt_str . number_format($money, 2, '.', '') . $order_codes . $receipt_info;
        return strtoupper(md5($accept_key));
    }

    /**
     * 回调时使用：校验key
     * @param $key
     * @param $order_codes
     * @param $money
     * @return bool
     */
    public function notifyCheckKey($key, $trade_no, $pay_status)
    {
        $accept_key = $this->czbank_encrypt_str . $trade_no . $pay_status;
        return strtoupper(md5($accept_key)) == strtoupper($key) ? true : false;
    }

    /**
     * 回调时使用：生成key
     * @param $order_codes
     * @param $money
     * @return string
     */
    public function notifyGenerateKey($trade_no)
    {
        $accept_key = $this->czbank_encrypt_str . $trade_no;
        return strtoupper(md5($accept_key));
    }

    /**
     * 通知放款
     *
     */
    public function generateLoanKey($trade_no, $czbank_no)
    {
        $accept_key = $this->czbank_encrypt_str . $trade_no . $czbank_no;
        return strtoupper(md5(strtoupper(md5($accept_key))));
    }
}